import { BaseService, CoolCommException } from "@cool-midway/core";
import { Inject, Provide } from "@midwayjs/core";
import { Repository } from "typeorm";
import { StorageInfoEntity } from "../entity/info";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { AddStorageInfoDTO, AuditStorageInfoDTO } from "../dto/info";
import { Context } from "@midwayjs/koa";
import { ProductInfoEntity, ProductStatus } from "../../product/entity/info";
import { CommonAuditStatus } from "../../../interface";

@Provide()
export class StorageInfoService extends BaseService {

    @InjectEntityModel(StorageInfoEntity)
    storageInfoModel: Repository<StorageInfoEntity>


    @InjectEntityModel(ProductInfoEntity)
    productInfoModel: Repository<ProductInfoEntity>

    @Inject()
    ctx: Context

    /**
     * 上架产品到云仓
     * @param dto 上架产品DTO
     * @returns 上架产品信息
     */
    async add(dto: AddStorageInfoDTO) {
        const { productId, expireDate, status } = dto
        const tenantId = this.ctx.provider?.tenantId

        // 获取产品详情
        const productInfo = await this.productInfoModel.findOne({ where: { id: productId, tenantId } })
        if (!productInfo) {
            throw new CoolCommException('产品不存在')
        }

        if (productInfo.status !== ProductStatus.ON_SALE) {
            throw new CoolCommException('产品状态不正确，请先上架产品')
        }

        // 判断是否已上架到云仓

        const isExists = await this.storageInfoModel.exists({ where: { productId } })
        if (isExists) {
            throw new CoolCommException('产品已上架到云仓')
        }

        // 创建云仓产品信息
        return await this.storageInfoModel.save({
            productId,
            sharedByTenantId: tenantId,
            expireDate,
            status,
        })
    }

    /**
     * 审核云仓产品
     * @param id 云仓产品ID
     * @param status 状态
     * @param rejectReason 驳回原因
     * @returns 审核云仓产品
     */
    async audit(dto: AuditStorageInfoDTO) {
        const { id, status, rejectReason } = dto
        const storageInfo = await this.storageInfoModel.findOne({ where: { id } })
        if (!storageInfo) {
            throw new CoolCommException('云仓产品不存在')
        }
        if (storageInfo.status !== CommonAuditStatus.PENDING) {
            throw new CoolCommException('云仓产品状态不正确')
        }
        return await this.storageInfoModel.update(id, { status, rejectReason })
    }
}